package com.lcifn.zk.console.support;

import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * zk session support util
 * @author LC
 * @date 2020/6/16 20:35
 */
@Component
public class ZkSessionSupport {

    // zkAddress - ZkSession Map
    private Map<String, ZkSession> addressSessionMap = new ConcurrentHashMap<>();
    // sessionId - ZkSession Map
    private Map<String, ZkSession> sessionIdMap = new ConcurrentHashMap<>();

    /**
     * 检查zk是否能连接
     * @param zkAddress
     * @return
     */
    public boolean checkConnection(String zkAddress) {
        return new CuratorZkConnection().checkConnection(zkAddress);
    }

    /**
     * 获取zkSession
     * @param zkAddress
     * @return
     */
    public ZkSession buildSession(String zkAddress) {
        ZkSession zkSession = addressSessionMap.get(zkAddress);
        if (zkSession != null) {
            return zkSession;
        }

        ZkSession session = new CuratorZkConnection().connect(zkAddress);
        addressSessionMap.put(zkAddress, session);
        sessionIdMap.put(session.getSessionId(), session);
        return session;
    }

    /**
     * zk地址获取ZkSession
     * @param zkAddress
     * @return
     */
    public ZkSession getSession(String zkAddress) {
        Assert.notNull(zkAddress, "zkAddress is null");
        ZkSession zkSession = addressSessionMap.get(zkAddress);
        if (zkSession == null) {
            zkSession = buildSession(zkAddress);
        }
        return zkSession;
    }
}
